package org.example.algorithm.backtracking;

import java.util.ArrayList;
import java.util.List;

public class PartitionSolution {
    private List<List<String>> ans = new ArrayList<>();
    private List<String> item = new ArrayList<>();

    public static void main(String[] args) {
        String s = "aba";
        PartitionSolution solution = new PartitionSolution();
        List<List<String>> res = solution.partition(s);
        System.out.println(res);
    }


    //aabaaccaadd
    public List<List<String>> partition(String s) {
        int len = s.length();
        if (len == 0) {
            return ans;
        }
        dfs(s, 0, 0);
        return ans;
    }

    private void dfs(String s, int start, int end) {
        if (end == s.length()) {
            ans.add(new ArrayList<>(item));
            return;
        }
        if (end < s.length() - 1) {
            dfs(s, start, end+1);
        }
        if (palindrome(s, start, end)) {
            item.add(s.substring(start, end+1));
            dfs(s, end+1, end+1);
            item.remove(item.size()-1);
        }
    }

    private boolean palindrome(String s, int start, int end) {
        int left = start;
        int right = end;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }


}
